<template>
  <div class="app-container">
    <div class="container" style="width: 100%;" v-if="!showAddStatus">
      <div class="filter-container">
        <el-form ref="queryForm" :model="listQuery" :rules="queryRules" label-position="left">
          <el-form-item size="mini" prop="title" style="float: left;">
            <el-input v-model="listQuery.title" placeholder="景点名称" class="filter-item" style="width: 160px;margin-right:5px;"></el-input>
          </el-form-item>
          <el-form-item size="mini" prop="type_sub_id" style="float: left;">
            <el-select v-model="listQuery.type_sub_id" placeholder="请选择" style="width: 160px;margin-right:5px;">
              <el-option label="所有" value=""></el-option>
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item size="mini" prop="country" style="float: left;">
            <el-select v-model="listQuery.country" placeholder="请选择" style="width: 160px;margin-right:5px;">
              <el-option label="所有" value=""></el-option>
              <el-option
                v-for="item in countryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item size="mini" style="float: left;">
            <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="getList">查询</el-button>
            <el-button v-waves size="mini" class="filter-item" type="danger" @click="resetQueryForm('queryForm')">重置</el-button>
          </el-form-item>
          <div style="float: right;margin-right: 60px">
            <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd()">添加景点</el-button>
          </div>
        </el-form>
      </div>
      <el-table v-loading="listLoading" :data="list" size="mini" highlight-current-row style="width: 100%">
        <el-table-column width="90px" align="left" label="ID">
          <template slot-scope="{row}">
            <span>{{ row.Id }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="名称">
          <template slot-scope="{row}">
            <span>{{ row.Title }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="分类">
          <template slot-scope="{row}">
            <span>{{ row.TypeSubTitle }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" width="150px" label="省">
          <template slot-scope="{row}">
            <span>{{ row.ProvinceTitle }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100px" align="left" label="市">
          <template slot-scope="{row}">
            <span>{{ row.CityTitle }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="门票">
          <template slot-scope="{row}">
            <i class="el-icon-check" style="color: green" v-if="row.FeeTicketHas"></i>
            <i class="el-icon-close" style="color: red" v-if="!row.FeeTicketHas"></i>
          </template>
        </el-table-column>
        <el-table-column align="left" label="开放时间">
          <template slot-scope="{row}">
            <span>{{ row.OpenTime }} - {{ row.CloseTime }}</span>
          </template>
        </el-table-column>

        <el-table-column align="left" label="热门">
          <template slot-scope="{row}">
            <el-switch
              v-model="row.IsHot"
              @change="handleHot(row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="left" label="推荐">
          <template slot-scope="{row}">
            <el-switch
              v-model="row.IsRecommend"
              @change="handleRecommend(row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="left" label="状态">
          <template slot-scope="{row}">
            <i class="el-icon-check" style="color: green" v-if="row.Status"></i>
            <i class="el-icon-close" style="color: red" v-if="!row.Status"></i>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="{row}">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleStatus(row.Id)"
            >
              <span v-if="row.Status">禁用</span>
              <span v-if="!row.Status">启用</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="+total > 0" :total="total" :page.sync="listQuery.page_index" :limit.sync="listQuery.page_size" @pagination="getList" style="margin-top: 1px; padding-top: 10px;" />
    </div>
    <div v-if="showAddStatus" class="container" style="width: 100%;">
      <el-page-header :content="isEdit ? '编辑 景点 信息' : '新增 景点 信息'" @back="goBack"></el-page-header>
      <el-form ref="addShGoodsForm" :rules="rules" :model="addData" label-position="left" label-width="90px" style="width: 100%; margin-top: 15px;">
        <el-container style="height: 760px; border: 1px solid #eee">
          <el-main style="margin-right:30px; width: 40%">
            <el-form-item label="景点类型" prop="type_sub_id">
              <el-select v-model="addData.type_sub_id" placeholder="请选择" style="width: 160px;margin-right:5px;">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="中文名称" prop="title">
              <el-input v-model="addData.title" placeholder="不可有HTML标签" style="width: 580px;"/>
            </el-form-item>
            <el-form-item label="英文名称" prop="title_en">
              <el-input v-model="addData.title_en" placeholder="不可有HTML标签" style="width: 580px;"/>
            </el-form-item>
            <el-form-item label="景点标签" prop="tags">
              <el-input v-model="addData.tags" placeholder="逗号隔开,最多6个汉字,最多4个标签, 汉字,数字,字母,下划线" style="width: 580px;"/>
            </el-form-item>
            <el-form-item label="景点描述" prop="content">
              <el-input v-model="addData.content" :rows="10" type="textarea" style="width: 580px;"/>
            </el-form-item>
            <el-form-item label="列表图片" prop="image_list">
              <el-upload
                class="avatar-uploader"
                :action="imageUploadUrl"
                list-type="picture-card"
                :headers="uploadHeader"
                :file-list="editInitImageList"
                :before-upload="beforeAvatarUpload"
                :on-success="handleUploadListImageSuccess"
                :on-preview="handleImagePreview"
                :on-remove="handleImageRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogImagePreviewVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-main>
          <el-aside style="background-color: #ffffff; width: 56%;">
            <el-form-item label="所在省市" size="mini" prop="province_city">
              <el-cascader
                style="width: 300px;"
                v-model="tmpDistrict"
                :options="districtOptions"
                @change="handleDistrictChange"></el-cascader>
            </el-form-item>
            <el-form-item label="景点地址" size="mini" prop="address" style="width: 390px;">
              <el-input type="textarea" v-model="addData.address" placeholder="具体地址"/>
            </el-form-item>
            <el-form-item label="开放时间" size="mini" prop="open_time">
              <el-time-select
                style="width: 145px;"
                placeholder="开始时间"
                v-model="addData.open_time"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00'
                }"
              >
              </el-time-select>
              -
              <el-time-select
                style="width: 145px;"
                placeholder="结束时间"
                v-model="addData.close_time"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00',
                  minTime: addData.open_time
                }"
              >
              </el-time-select>
            </el-form-item>
            <el-form-item label="景点门票" size="mini" prop="fee_ticket_has" style="width: 325px;">
              <el-radio-group v-model="addData.fee_ticket_has">
                <el-radio-button :label="1">免费</el-radio-button>
                <el-radio-button :label="2">收费</el-radio-button>
              </el-radio-group>
              <el-input style="margin-top: 5px;" v-if="addData.fee_ticket_has" v-model="addData.fee_amount" placeholder="费用说明"/>
            </el-form-item>
            <el-form-item label="收费项目" size="mini" prop="fee_inner_has" style="width: 325px;">
              <el-radio-group v-model="addData.fee_inner_has">
                <el-radio-button :label="1">无</el-radio-button>
                <el-radio-button :label="2">有</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="官方电话" size="mini" prop="" style="width: 325px;">
              <el-input v-model="addData.phone" placeholder="填写电话"/>
            </el-form-item>
            <el-form-item label="官方网站" size="mini" prop="" style="width: 325px;">
              <el-input v-model="addData.website" placeholder="填写官网"/>
            </el-form-item>
            <el-form-item label="位置经度" size="mini" prop="coordinate_x">
              <div style="float: left; width: 110px"><el-input v-model="addData.coordinate_x" placeholder="填写经度"/></div><div style="float: left; margin: 0px 5px;">-</div>
              <div style="float: left; width: 110px"><el-input v-model="addData.coordinate_y" placeholder="填写维度"/></div>
            </el-form-item>
            <el-form-item label="位置Code" size="mini" prop="plus_code" style="width: 325px;">
              <el-input v-model="addData.plus_code" placeholder="填写谷歌 plus code"/>
            </el-form-item>
            <el-form-item label="封面图片" prop="image_cover">
              <el-upload
                class="avatar-uploader"
                :action="imageUploadUrl"
                :show-file-list="false"
                :headers="uploadHeader"
                :data="{type: 'cover'}"
                :on-preview="handleImagePreview"
                :on-success="handleUploadCoverImageSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageCoverUrl" :src="imageCoverUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <div>
              <el-button style="float: right; margin-right: 100px;" size="mini" type="primary" @click="handleAddSubmit()">提交</el-button>
            </div>
          </el-aside>
        </el-container>
      </el-form>
    </div>
  </div>
</template>

<script>
import { convenientElementList, convenientElementAdd, convenientElementStatus, convenientElementUploadImage, convenientElementHot, convenientElementRecommend } from '@/api/urban'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination/index'
import { getToken } from '@/utils/auth'
import { cleanObjectTreeData, strLength } from '@/utils/common'
import { checkCanAccess } from '@/utils/permission'

export default {
  name: 'ConvenientElement',
  components: { Pagination },
  directives: { waves },
  data() {
    const checkTitle = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起，物品标题不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 72 || strLen < 6) {
        return callback(new Error('对不起，标题为6-72个字符, 汉字为3个字符!'))
      } else {
        callback()
      }
    }
    const checkTags = function(rule, value, callback) {
      if (!value) {
        callback()
        return
      }

      // 检测单个标签的长度
      const tags = value.split(',')
      for (let i = 0; i < tags.length; i++) {
        const strLen = strLength(tags[i])
        if (strLen > 18 || strLen < 6) {
          return callback(new Error('对不起， 单个标签长度为6-18个字符,汉字为3个字符!'))
        }
      }

      // 检测标签的字符构成
      const reg = /^[,_A-Za-z0-9\u4e00-\u9fa5]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 标签只能包含汉字,数字,字母,下划线,逗号'))
      } else {
        callback()
      }
    }
    return {
      // 副文本配置
      customConfig: {
        body_class: 'goods_id',
        height: 500,
        plugins: 'image',
        toolbar: 'image',
        images_upload_url: '',
        images_upload_handler: function(blobInfo, success, failure) {
          const imageData = new FormData()
          imageData.append('file', blobInfo.blob(), blobInfo.filename())
          convenientElementUploadImage(imageData).then(res => {
            if (res.success) {
              success(res.data.file_url)
            }
          })
        }
      },
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page_index: 1,
        page_size: 10,
        title: '',
        type_id: 5,
        type_sub_id: ''
      },
      addData: {
        id: 0,
        type_id: 5,
        type_sub_id: '',
        title: '',
        title_en: '',
        summary: '',
        content: '',
        close_time: '',
        open_time: '',
        open_week_day: '',
        fee_ticket_has: '1',
        fee_inner_has: '1',
        fee_amount: '',
        province_id: '',
        city_id: '',
        circle_id: '',
        address: '',
        phone: '',
        website: '',
        coordinate_x: '',
        coordinate_y: '',
        plus_code: '',
        tags: ''
      },
      countryOptions: [],
      typeOptions: [],
      districtOptions: [],
      tmpDistrict: [],
      tmpTime: [],
      showAddStatus: false,
      isEdit: false,
      rules: {
        province_city: [
          { required: false, message: '需要选择省市', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        type_sub_id: [
          { required: true, message: '需要选择类型', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '需要填写中文标题', trigger: 'blur' },
          { validator: checkTitle, trigger: 'blur' }
        ],
        title_en: [
          { required: true, message: '需要填写英文标题', trigger: 'blur' },
          { validator: checkTitle, trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '需要填写标签', trigger: 'blur' },
          { validator: checkTags, trigger: 'blur' }
        ],
        content: [
          { required: true, message: '需要填写物品描述', trigger: 'blur' }
        ],
        coordinate_x: [
          { required: true, message: '需要填写经度', trigger: 'blur' }
        ],
        coordinate_y: [
          { required: true, message: '需要填写维度', trigger: 'blur' }
        ],
        plus_code: [
          { required: true, message: '需要填写谷歌plus code', trigger: 'blur' }
        ],
        open_time: [
          { required: true, message: '需要填写开放时间', trigger: 'blur' }
        ],
        close_time: [
          { required: true, message: '需要填写结束时间', trigger: 'blur' }
        ],
        fee_inner_has: [
          { required: true, message: '需要选择是否需要购买门票', trigger: 'blur' }
        ],
        fee_ticket_has: [
          { required: true, message: '需要选择是否有收费项目', trigger: 'blur' }
        ]
      },
      queryRules: {
        type_sub_id: [
          { required: false, message: '需要选择子类型', trigger: 'blur' }
        ],
        type_id: [
          { required: false, message: '需要选择类型', trigger: 'blur' }
        ],
        title: [
          { required: false, message: '需要选择标题', trigger: 'blur' }
        ]
      },
      dialogImageUrl: '',
      imageCoverUrl: '',
      tmpUploadImageList: [],
      editInitImageList: [],
      imageUploadUrl: process.env.VUE_APP_BASE_API + 'urban/tour/uploadImage',
      dialogImagePreviewVisible: false
    }
  },
  computed: {
    uploadHeader() {
      return { Authorization: 'bearer ' + getToken() }
    }
  },
  created() {
    this.resetQueryData()
    this.resetAddData()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      convenientElementList(this.listQuery).then(response => {
        if (response.success) {
          this.list = response.data.data
          this.total = response.data.total
          this.typeOptions = response.data.type_options
          this.countryOptions = response.data.country_options
          this.districtOptions = cleanObjectTreeData(response.data.district_options)
          setTimeout(() => {
            this.listLoading = false
          }, 300)
        } else {
          this.$message({
            type: 'error',
            message: response.msg
          })
          setTimeout(() => {
            this.listLoading = false
          }, 100)
        }
      })
    },
    getDetail(item) {
      this.addData.id = item.Id
      this.addData.type_sub_id = item.TypeSubId
      this.addData.title = item.Title
      this.addData.title_en = item.TitleEn
      this.addData.content = item.Content
      this.addData.summary = item.summary
      this.addData.tags = item.Tags
      this.addData.open_time = item.OpenTime
      this.addData.close_time = item.CloseTime

      this.addData.fee_inner_has = item.FeeInnerHas === 0 ? 1 : 2
      this.addData.fee_ticket_has = item.FeeTicketHas === 0 ? 1 : 2
      this.addData.fee_amount = item.FeeAmount

      this.addData.address = item.Address
      this.addData.province_id = item.ProvinceId
      this.addData.city_id = item.CityId
      this.tmpDistrict = [item.ProvinceId, item.CityId]
      this.addData.coordinate_x = item.CoordinateX
      this.addData.coordinate_y = item.CoordinateY
      this.addData.plus_code = item.PlusCode

      this.addData.image_cover = item.ImageCover
      this.imageCoverUrl = item.ImageCoverUrl
      this.addData.image_list = item.ImageList
      this.editInitImageList = item.ImageListArr
    },
    handleAdd() {
      this.isEdit = false
      this.showAddStatus = true
      this.resetAddData()
    },
    handleEdit(item) {
      this.isEdit = true
      this.showAddStatus = true
      this.getDetail(item)
    },
    handleAddSubmit() {
      this.$refs['addShGoodsForm'].validate((valid) => {
        if (valid) {
          convenientElementAdd(this.addData).then((response) => {
            if (response.success === true) {
              this.$message({
                type: 'success',
                message: '添加二手商品信息成功'
              })
              this.goBack()
              this.getList()
              this.resetAddData()
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
      })
    },
    handleStatus(id) {
      console.log(id)
      this.$confirm('此操作将下架指定物品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        convenientElementStatus(id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: response.msg
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleHot(row) {
      let tipMsg = '取消热点景点'
      if (row.IsHot === true) {
        tipMsg = '设置成热点景点'
      }

      this.$confirm('此操作将目标 ' + tipMsg + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        convenientElementHot(row.Id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: response.msg
            })

            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleRecommend(row) {
      let tipMsg = '取消景点推荐'
      if (row.IsRecommend === true) {
        tipMsg = '设置成推荐景点'
      }

      this.$confirm('此操作将目标 ' + tipMsg + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        convenientElementRecommend(row.Id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: response.msg
            })

            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetAddData() {
      this.imageCoverUrl = ''
      this.tmpUploadImageList = []
      this.isEdit = false
      this.addData = {
        id: 0,
        type_id: 5,
        type_sub_id: '',
        title: '',
        title_en: '',
        summary: '',
        content: '',

        close_time: '',
        open_time: '',
        open_week_day: '',
        fee_ticket_has: '1',
        fee_inner_has: '1',
        fee_amount: '',
        country_id: '',
        province_id: '',
        city_id: '',
        circle_id: '',
        address: '',
        phone: '',
        website: '',
        coordinate_x: '',
        coordinate_y: '',
        plus_code: '',
        tags: ''
      }
    },
    resetQueryData() {
      this.listQuery = {
        page_index: 1,
        page_size: 10,
        title: '',
        type_id: 5,
        type_sub_id: ''
      }
    },
    resetQueryForm(formName) {
      this.$refs[formName].resetFields()
    },
    beforeAvatarUpload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传封面图片只能是 JPG/PNG 格式!')
        return false
      }

      if (file.size / 1024 > 300) {
        this.$message.error('上传封面图片大小不能超过 300K!')
        return false
      }
      return true
    },
    checkCanAccess(path) {
      return checkCanAccess(path)
    },
    goBack() {
      this.showAddStatus = false
      this.resetAddData()
    },
    handleDistrictChange(item) {
      if (item.length > 1) {
        this.addData.province_id = item[0]
        this.addData.city_id = item[1]
      }
    },
    handleUploadCoverImageSuccess(res, file) {
      if (res.success) {
        this.addData.image_cover = res.data.file_name
        this.imageCoverUrl = URL.createObjectURL(file.raw)
      } else {
        this.$message({
          type: 'error',
          message: '上传图片失败'
        })
      }
    },
    handleUploadListImageSuccess(res, file, fileList) {
      if (res.success) {
        const imageNameList = []
        for (let i = 0; i < fileList.length; i++) {
          if ('image_name' in fileList[i]) {
            imageNameList.push(fileList[i].image_name)
          } else {
            imageNameList.push(fileList[i].response.data.file_name)
          }
        }
        this.addData.image_list = imageNameList.join(',')
      } else {
        this.$message({
          type: 'error',
          message: '上传图片失败'
        })
      }
    },
    handleImageRemove(file, fileList) {
      const imageNameList = []
      for (let i = 0; i < fileList.length; i++) {
        imageNameList.push(fileList[i].response.data.file_name)
      }
      this.addData.image_list = imageNameList.join(',')
    },
    handleImagePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImagePreviewVisible = true
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 108px;
  height: 108px;
  line-height: 108px;
  text-align: center;
}
.avatar {
  width: 108px;
  height: 108px;
  display: block;
}
.el-upload-list--picture-card .el-upload-list__item {
  width: 108px;
  height: 108px;
}
.el-upload--picture-card {
  width: 108px;
  height: 108px;
  line-height: 108px;
}
</style>
